import TOTP,config
import rsa,requests
#import online_jsrun
from lxml import etree
def run(isopenweb:bool = True)->str|requests.Session:
    print(f"isopenweb:{isopenweb}")
    toml = config.gtoml()
    name = toml["setting"]["vpnname"]
    password = toml["setting"]["vpnpassword"]
    if name == "" or password == "":
        password = toml["setting"]["password"]
        name = toml["setting"]["name"]
        
    key = toml["setting"]["key"]
    session = requests.Session()
    session.trust_env =True
    session.verify = False
    header =  {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "content-type": "application/x-www-form-urlencoded",
        "sec-ch-ua": "\"Not)A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"127\", \"Chromium\";v=\"127\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0",
        "sec-fetch-site": "same-origin"
    }
    # 第一步：获取 CSRF_RAND_CODE 和 TwfID
    url_auth = 'https://webvpn.stu.edu.cn/por/login_auth.csp?apiversion=1'
    response_auth = session.get(url_auth,headers=header)
    #print(response_auth.text)
    if response_auth.status_code != 200:
        return "访问webvpn失败,请检查是否连接WiFi"
    xml_data = response_auth.content
    #使用 lxml 的 fromstring 方法解析 XML
    root = etree.fromstring(xml_data)

    # 获取 CSRF_RAND_CODE
    csrf_rand_code = root.find('.//CSRF_RAND_CODE').text
    # 获取 TwfID
    twfid = root.find('.//TwfID').text

    # 第二步：登录
    url_login = 'https://webvpn.stu.edu.cn/por/login_psw.csp?anti_replay=1&encrypt=1&apiversion=1'
    #js = open('pwd2.js').read().replace("2546168529",f"{password}_{csrf_rand_code}")
    #pwd1 = online_jsrun.runjs(js).replace("\n","")
    pwd2 = rsa.getpwds(password,csrf_rand_code)
    #print({"pwd1": pwd1, "pwd2": pwd2})
    data_login = {
        'mitm_result': '',  
        'svpn_req_randcode': csrf_rand_code,
        'svpn_name': name,  
        'svpn_password': pwd2,  
        'svpn_rand_code': ''  
    }

    response_login = session.post(url_login, data=data_login,headers=header)
    #print(response_login.text)
    if response_login.status_code != 200:
       return "可能多次输入错密码出现了验证码，请自己手动登录一次webvpn"
    elif response_login.text.find("锁定") != -1:
        return "认证错误次数过多，被系统锁定"
    # 第三步：输入动态口令
    passkey = TOTP.gettotpkey(key)
    url_token = 'https://webvpn.stu.edu.cn/auth/token?apiversion=1'
    data_token = {
        'twfid': twfid,
        'svpn_inputtoken': passkey 
    }
    response_token = session.post(url_token, data=data_token,headers=header)
    #print(response_token.text)

    cookies = session.cookies
    cookies_v = ""
    for co in cookies:
        if(co.name == "TWFID"):
            cookies_v = co.value
    if cookies_v == "":
        return("未成功获取到TWFID，请检查key是否输入正确")
    import webbrowser

    web = toml["setting"]["web"]
    noyouhou = toml["setting"]["noyouhou"]
    toml["setting"]["twfid"] = cookies_v
    config.wtoml(toml)
    if web != "" and isopenweb:
        try:
            if noyouhou == "yes":
                webbrowser.open(f"https://webvpn.stu.edu.cn/portal/shortcut.html?twfid={cookies_v}&url={web}")
            else:
                webbrowser.open(f"{web}setcookies{cookies_v}TWFID")
        except:
            webbrowser.open(f"{web}setcookies{cookies_v}TWFID")#若没有该项默认使用油猴
    return session